package com.ma.springframework.beans.factory.support;

import com.ma.springframework.beans.BeansException;
import com.ma.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) {
         Class clazz = beanDefinition.getBeanClass();
         try {
             if (null != ctor){
                 return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
             }else {
                 return clazz.getDeclaredConstructor().newInstance();
             }
         }catch (NoSuchMethodError | InstantiationError | IllegalAccessException | InvocationTargetException e){
             throw new BeansException("failed to instantiate ["+clazz.getName()+"]",e);
         } catch (InstantiationException e) {
             e.printStackTrace();
         } catch (NoSuchMethodException e) {
             e.printStackTrace();
         }
         return null;
    }
}
